package com.weilele.mvvm.utils.download

import com.weilele.mvvm.utils.printStackTrace
import okhttp3.MediaType
import okhttp3.ResponseBody
import okio.*

//设置了这个拦截可以直接在响应里面读取，否则会读取完网络数据才有响应
class ProgressResponseBody(private val responseBody: ResponseBody,
                           val onError: Function1<Throwable, Unit>) : ResponseBody() {
    private val bufferedSource: BufferedSource = source(responseBody.source()).buffer()

    override
    fun contentType(): MediaType? {
        return responseBody.contentType()
    }

    override
    fun contentLength(): Long {
        return responseBody.contentLength()
    }

    override
    fun source(): BufferedSource {
        return bufferedSource
    }

    private fun source(source: Source): Source {
        return object : ForwardingSource(source) {
            var totalBytesRead = 0L
            override fun read(sink: Buffer, byteCount: Long): Long {
                return try {
                    val bytesRead = super.read(sink, byteCount)
                    // read() returns the number of bytes read, or -1 if this source is exhausted.
                    totalBytesRead += if (bytesRead != -1L) bytesRead else 0
//                        val total = responseBody.contentLength()
//                       progressListener.update(totalBytesRead, responseBody.contentLength(), bytesRead == -1L)
//                        progressListener?.invoke(totalBytesRead, total, null)
                    bytesRead
                } catch (e: Throwable) {
                    printStackTrace { e }
                    //下载失败
                    onError.invoke(e)
                    -1
                }
            }
        }
    }
}